package com.example.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.mapper.SysJobMapper;
import com.example.po.SysJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class SysJobServiceImpl extends ServiceImpl<SysJobMapper, SysJob> implements SysJobService {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Value("${sys.server.max-retry-count}")
    private int maxRetryCount;

    @Resource
    private SysServerService sysServerService;

    /***
     * 获取运行中的任务列表
     * @param maxCount
     * @return
     */
    @Override
    public List<SysJob> getRunningJobList(int maxCount) {
        return getBaseMapper().getJobList(sysServerService.getServerKey(), maxCount, this.maxRetryCount, new Date());
    }

    /***
     * 把任务分配给节点
     * @param size
     * @param index
     * @param serverKey
     */
    @Override
    public void updateJobServerKey(int size, int index, Long serverKey) {
        getBaseMapper().updateJobServerKey(size, index, serverKey);
    }

    /***
     * 把掉线节点未完成的任务转移给其他节点
     * @param size
     * @param index
     * @param sourceServerKey
     * @param targetServerKey
     */
    @Override
    public void updateJobServerKey(int size, int index, Long sourceServerKey, Long targetServerKey) {
        getBaseMapper().updateJobServerKeyToOther(size, index, sourceServerKey, targetServerKey, maxRetryCount);
    }

    /***
     * 抓取已完成的任务列表归档
     * @param maxSize
     * @return
     */
    @Override
    public List<SysJob> getFinishJobs(int maxSize) {
        return getBaseMapper().getFinishJobs(maxSize, maxRetryCount);
    }
}
